//------------------------------------------------------------------------------
#include <QMessageBox>
#include "CEntreesSortiesDeStockFrm.h"
#include "CMySQL.h"
//------------------------------------------------------------------------------
CEntreesSortiesDeStockFrm::CEntreesSortiesDeStockFrm(QString codeArticle, double stockActuel, QWidget *parent) : QDialog(parent)
{
	setupUi(this);
	
	_article=codeArticle;
	article->setText(codeArticle);
	stock->setText(QString("%1").arg(stockActuel, 0, 'f', 2));
	
	mouvement->addItem(tr("Remplacement"));
	mouvement->addItem(tr("Entrée"));
	mouvement->addItem(tr("Sortie"));
}
//------------------------------------------------------------------------------
void CEntreesSortiesDeStockFrm::accept(void)
{
	QString requete;
	
	if(quantite->text().toDouble() == 0 && mouvement->currentIndex() != 0)
	{
		QMessageBox msgBox(	QMessageBox::Warning, tr("Attention"), 
							tr("Qunatité en mouvement incorrect"), QMessageBox::Ok);
		msgBox.exec();	
		
		return;
	}
	
	switch(mouvement->currentIndex())
	{
		case 0: //remplacement
			requete="INSERT INTO mouvementStock (article, dateMouvement, qui, stockAvant, mouvement) ";
			requete+="SELECT code, CURDATE(), \""+CMySQL::getInstance()->getUser()+"\", stock, ";
			requete+=QString::number(quantite->text().toDouble())+"-stock FROM article WHERE code = \""+_article+"\" ";
			
			CMySQL::getInstance()->execQuery(requete);
			
			requete="UPDATE article SET stock="+QString::number(quantite->text().toDouble())+" WHERE code = \""+_article+"\" ";
			break;
		case 1: //entrée
			requete="INSERT INTO mouvementStock (article, dateMouvement, qui, stockAvant, mouvement) ";
			requete+="SELECT code, CURDATE(), \""+CMySQL::getInstance()->getUser()+"\", stock, "+QString::number(quantite->text().toDouble())+" ";
			requete+="FROM article WHERE code = \""+_article+"\" ";
			
			CMySQL::getInstance()->execQuery(requete);
			
			requete="UPDATE article SET stock=stock+"+QString::number(quantite->text().toDouble())+" WHERE code = \""+_article+"\" ";
			break;
		case 2: //sortie
			requete="INSERT INTO mouvementStock (article, dateMouvement, qui, stockAvant, mouvement) ";
			requete+="SELECT code, CURDATE(), \""+CMySQL::getInstance()->getUser()+"\", stock, -"+QString::number(quantite->text().toDouble())+" ";
			requete+="FROM article WHERE code = \""+_article+"\" ";
			
			CMySQL::getInstance()->execQuery(requete);
			
			requete="UPDATE article SET stock=stock-"+QString::number(quantite->text().toDouble())+" WHERE code = \""+_article+"\" ";
			break;
		default:
			break;
	}
	
	CMySQL::getInstance()->execQuery(requete);
	
	QDialog::accept();
}
//------------------------------------------------------------------------------